package com.xlf.service.base.service.impl;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xlf.common.core.constant.Constants;
import com.xlf.common.core.exception.BizException;
import com.xlf.common.core.util.StringUtils;
import com.xlf.pojo.base.Difficulty;
import com.xlf.pojo.base.Problem;
import com.xlf.pojo.base.ProblemTag;
import com.xlf.pojo.base.Tag;
import com.xlf.service.base.mapper.ProblemTagMapper;
import com.xlf.service.base.mapper.TagMapper;
import com.xlf.service.base.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.List;

/**
 * @author 小新
 * @description 针对表【tag】的数据库操作Service实现
 * @createDate 2023-10-03 09:52:13
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
        implements TagService {

    @Resource
    ProblemTagMapper problemTagMapper;


    @Override
    public List<Tag> getList() {
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Tag::getId,Tag::getName,Tag::getColor)
                .eq(Tag::getStatus, Constants.NORMAL);
        return list(wrapper);
    }

    @Override
    public List<Tag> getList(Tag tag) {

        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(StringUtils.isNotEmpty(tag.getName()),Tag::getName,tag.getName())
                .eq(tag.getStatus()!=null,Tag::getStatus,tag.getStatus());

        List<Tag> list = list(wrapper);

        if(StringUtils.isNotEmpty(list)){
            list.forEach(item -> {
                Long aLong = problemTagMapper.selectCount(new LambdaQueryWrapper<ProblemTag>()
                        .eq(ProblemTag::getTagId,item.getId()));
                item.setProblemNum(Math.toIntExact(aLong));
            });
        }
        return list;
    }

    @Transactional
    @Override
    public void delete(List<String> ids) {
        Assert.notNull(ids,() -> new BizException("列表不能为空"));
        ids.forEach(item -> {
            Long count = problemTagMapper.selectCount(new LambdaQueryWrapper<ProblemTag>()
                    .eq(ProblemTag::getTagId, item));
            if(count > 0){
                throw new BizException("该标签下存在题目，不允许删除！");
            }
        });
        removeBatchByIds(ids);
        return;
    }

    @Override
    public boolean updateStatus(Tag tag) {
        return lambdaUpdate().set(Tag::getStatus,tag.getStatus()).eq(Tag::getId,tag.getId()).update();

    }


}




